package org.example.springchatroom.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.springchatroom.constants.Constants;
import org.example.springchatroom.mapper.MessageMapper;
import org.example.springchatroom.mapper.MessageSessionMapper;
import org.example.springchatroom.model.MessageSession;
import org.example.springchatroom.model.MessageSessionUser;
import org.example.springchatroom.model.Result;
import org.example.springchatroom.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/9/6
 * Time: 18:52
 */
@RestController
@RequestMapping("/message")
@Slf4j
public class MessageSessionController {
    @Autowired
    private MessageSessionMapper messageSessionMapper;
    @Autowired
    private MessageMapper messageMapper;

    @RequestMapping(value = "/getSessionList",method = RequestMethod.GET)
    public Result<List<MessageSession>> getSessionList(HttpServletRequest request) {
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        log.info("getSessionIdList接收到token:{}", token);
        Integer userId = JwtUtils.getIdByToken(token);
        log.info("getSessionIdList解析token,userId:{}", userId );
        //1.根据用户id查询会话列表
        List<Integer> sessionIdList = messageSessionMapper.getSessionIdList(userId);
        List<MessageSession> messageSessionList = new ArrayList<>();
        for (Integer sessionId : sessionIdList) {
            MessageSession messageSession = new MessageSession();
            messageSession.setSessionId(sessionId);
            messageSession.setFriends(messageSessionMapper.getFriendListBySessionId(sessionId, userId));
            //2.查询最新消息
            String lastMessage = messageMapper.getLastMessageBySessionId(sessionId);
            //3.判断是否有消息
            messageSession.setLastMessage(Objects.requireNonNullElse(lastMessage, ""));
            messageSessionList.add(messageSession);
        }
        return Result.success(messageSessionList);
    }

    @Transactional
    @RequestMapping("/createSession")
    public Result<Map<String,Integer>> addMessageSession(Integer toUserId,HttpServletRequest request) {
        Map<String,Integer> map = new HashMap<>();
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        log.info("addMessageSession接收到token:{}", token);
        Integer userId = JwtUtils.getIdByToken(token);
        log.info("addMessageSession解析token,userId:{}", userId );
        MessageSession messageSession = new MessageSession();
        MessageSessionUser  messageSessionUser1 = new MessageSessionUser();
        MessageSessionUser  messageSessionUser2 = new MessageSessionUser();
        try {
            Integer ret = messageSessionMapper.addMessageSession(messageSession);
            if (ret == 1) {
                log.info("创建会话成功,sessionId:{}", messageSession.getSessionId());
            }
            messageSessionUser1.setSessionId(messageSession.getSessionId());
            messageSessionUser1.setUserId(userId);
            Integer result1 = messageSessionMapper.addMessageSessionUser(messageSessionUser1);
            messageSessionUser2.setSessionId(messageSession.getSessionId());
            messageSessionUser2.setUserId(toUserId);
            Integer result2 = messageSessionMapper.addMessageSessionUser(messageSessionUser2);
            if (result1 == 1 &&  result2 == 1) {
                log.info("新增会话成功,sessionId:{},userId:{},toUserId:{}", messageSession.getSessionId(),userId, toUserId);
                map.put("sessionId", messageSession.getSessionId());
                return Result.success(map);
            }
        }catch (Exception e) {
            log.error("创建会话失败,e:{}",e.getMessage());
        }
        return Result.fail("创建会话失败");
    }
}
